const { addressApi } = require('../../utils/api/index.js')
Page({
  data: {
    addressList: [], // 地址列表
    fromOrder: false // 是否从订单页面跳转过来
  },

  onLoad(options) {
    this.setData({
      fromOrder: options.fromOrder === 'true'
    });
  },

  onShow() {
    this.loadAddressList();
  },

  onPullDownRefresh() {

  },

  // 加载地址列表
  async loadAddressList() {
    try {
      const param = {
        userId: '1837425962481504256'  //TODO 先写死，后续从token中拿  
      }
      const result = await addressApi.queryDeliveryAddressList(param);
      if (result.code === '0000') {
        this.setData({
          addressList: result.data
        });
      }else{
        wx.showToast({
          title: '获取收货地址失败：'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取收货地址失败：', error)
      wx.showToast({
        title: '获取收货地址失败',
        icon: 'none'
      })
    }
  },

  // 选择地址（从订单页面跳转过来时使用）
  selectAddress(e) {
    if (!this.data.fromOrder) return;
    
    const index = e.currentTarget.dataset.index;
    const address = this.data.addressList[index];
    
    // 返回上一页并带回调地址数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    prevPage.setData({
      selectedAddress: address
    });
    
    wx.navigateBack();
  },

  // 设置默认地址
  async setDefault(e) {
    const id = e.currentTarget.dataset.id;
    try {
      const param = {
        userId: '1837425962481504256',  //TODO 先写死，后续从token中拿  
        addressId: id,
        isDefault: 1
      };
      const result = await addressApi.setDefaultAddress(param);
      if (result.code === '0000') {
        var addressList = this.data.addressList;
        addressList.forEach(item =>{
          if(item.addressId === id){
            item.isDefault = 1;
          }else{
            item.isDefault = 0;
          }
        })
        this.setData({
          addressList: addressList
        });
      }else{
        wx.showToast({
          title: '设置默认地址失败：'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('设置默认地址失败：', error)
      wx.showToast({
        title: '设置默认地址失败',
        icon: 'none'
      })
    }
  },

  // 编辑地址
  editAddress(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/address/edit/edit?id=${id}`
    });
  },

  // 删除地址
  async deleteAddress(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: (res) => {
        if (res.confirm) {
          this.delAddr(id);
          //从addressList中删除
          var addressList = [];
          this.data.addressList.forEach(item =>{
            if(item.addressId != id){
              addressList.push(item);
            }
          });
          this.setData({
            addressList: addressList
          });
        }
      }
    });
  },
  //调用后台删除地址
  async delAddr(id){
    try{
      const result = await addressApi.deleteDeliveryAddress(id);
      if (result.code === '0000') {

      }else{
        wx.showToast({
          title: '删除地址失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除地址失败：', error)
      wx.showToast({
        title: '删除地址失败',
        icon: 'none'
      });
    }
  },

  // 添加新地址
  addAddress() {
    wx.navigateTo({
      url: `/pages/address/edit/edit`
    });
  }
});